# coding=utf-8
import requests
from loguru import logger
from fake_useragent import UserAgent


def send_http_request(domain: str):
    """
    发生 HTTP 请求
    :param domain:
    :return:
    """
    try:
        response = requests.get(f"http://{domain}", headers={'user-agent': UserAgent().random}, timeout=6)
        response.raise_for_status()
        return "http"

    except requests.exceptions.Timeout:
        logger.info(f"{domain} - 请求超时")
        return None

    except requests.exceptions.HTTPError as he:
        # 4xx、5xx 等错误
        logger.error(he)
        return None

    except requests.exceptions.RequestException as e:
        logger.error(e)
        return None


def send_https_request(domain: str):
    """
    使用 HTTPS 发送请求
    """
    try:
        response = requests.get(f"https://{domain}", headers={'user-agent': UserAgent().random}, timeout=6)
        response.raise_for_status()
        return 'https'

    except requests.exceptions.Timeout:
        logger.info(f"{domain} - 请求超时")
        return None

    except requests.exceptions.HTTPError as he:
        # 4xx、5xx 等错误
        logger.error(he)
        return None

    except requests.exceptions.RequestException:
        # 使用 HTTP 请求
        logger.info(f'HTTPS请求失败 -> 转HTTP请求')
        ret = send_http_request(domain)
        if ret is not None:
            return ret

        return None


def parse_protocol(domain: str):
    '''
    对没有协议的域名进行添加协议
    - 如果存在HTTPS或HTTP协议则判断该网址是否有效（是否正常备案）
    - 如果不存在则进行协议添加
        - 优先使用HTTPS协议
        - 其次使用HTTP协议
    返回的是带协议的域名
    '''
    try:
        response = requests.get(domain, headers={'user-agent': UserAgent().random}, timeout=6)
        response.raise_for_status()
        return domain

    except requests.exceptions.MissingSchema:
        # 缺少协议 优先使用 HTTPS
        ret = send_https_request(domain)
        if ret is not None:
            print(f"{ret}://{domain}")
            return

        return None

    except requests.exceptions.ConnectTimeout:
        logger.info(f"{domain} - 请求超时")
        return None

    except requests.exceptions.HTTPError as he:
        # 4xx、5xx 等错误
        logger.error(he)
        return None


if __name__ == '__main__':
    parse_protocol("125.35.235.10")
